/**
 * All Rights Reserved , Copyright (C) 2022 , 青岛鼎信通讯股份有限公司
 * <p>
 * MmsDeptProvinceCityMatchInfoController
 * 部门地市信息表
 * <p>
 * 修改纪录
 * 2022-02-22 版本：1.0 xinfushuo 创建。
 *
 * @version 版本：1.0
 * @author 作者：xinfushuo
 * 创建日期：2022-02-22
 */

package com.topscomm.mms.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.topscomm.basic.exception.BusinessException;
import com.topscomm.cbo.pojo.CboRoleEntity;
import com.topscomm.mms.MmsSystemConst;
import com.topscomm.mms.pojo.MmsDeptProvinceCityMatchInfoEntity;
import com.topscomm.mms.pojo.MmsProvinceCityMatchinfoEntity;
import com.topscomm.mms.service.impl.MmsDeptExtraInfoService;
import com.topscomm.mms.service.impl.MmsProvinceCityMatchinfoService;
import com.topscomm.pub.util.ConvertUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.topscomm.mms.controller.auto.MmsDeptProvinceCityMatchInfoControllerAuto;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.cbo.model.TreeModel;

/**
 * @author: xinfushuo
 * @date: 2022-02-22
 * @description:部门地市信息表Controller
 * @modify:
 */
@RestController
@RequestMapping("mms/deptProvinceCityMatchInfo")
public class MmsDeptProvinceCityMatchInfoController extends MmsDeptProvinceCityMatchInfoControllerAuto implements IMmsDeptProvinceCityMatchInfoController {
    private final MmsProvinceCityMatchinfoService mmsProvinceCityMatchinfoService;
    private final MmsDeptExtraInfoService mmsDeptExtraInfoService;

    public MmsDeptProvinceCityMatchInfoController(MmsProvinceCityMatchinfoService mmsProvinceCityMatchinfoService, MmsDeptExtraInfoService mmsDeptExtraInfoService) {
        this.mmsProvinceCityMatchinfoService = mmsProvinceCityMatchinfoService;
        this.mmsDeptExtraInfoService = mmsDeptExtraInfoService;
    }
    /**
     * @param paraMap
     * @return
     * @author: xinfushuo
     * @date: 2022-02-22
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    protected String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" 1=1 ");
        if (paraMap.containsKey("qry_deptcommoncode")) {
            String value = paraMap.get("qry_deptcommoncode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and {0} = '{1}' ", MmsDeptProvinceCityMatchInfoEntity.FieldDeptcommoncode, value);
        }
        if (paraMap.containsKey("qry_areaname")) {
            String value = paraMap.get("qry_areaname").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle("and {0} like '%{1}%' ", MmsDeptProvinceCityMatchInfoEntity.FieldAreaname, value);
        }
        if (paraMap.containsKey("qry_parentid")) {
            String value = paraMap.get("qry_parentid").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and parentid = '{0}' ", value);
        }
        List<CboRoleEntity> userRoleList = getUserBean().getRoleList();

        if (getUserBean().getUser().getAdminlevel() != 9 && (userRoleList.size() > 0 && !getUserBean().getRoleList().stream().map(role->role.getCode()).filter(Objects::nonNull).anyMatch(rolecode ->
               rolecode.contentEquals(MmsSystemConst.ItemsEnum.bspOperators)))) {
            String userDeptcommoncode = this.service.getDeptCommonCode(getUserBean().getDept().getCode());
            sql.appendSingle("AND {0} = '{1}'", MmsDeptProvinceCityMatchInfoEntity.FieldDeptcommoncode, userDeptcommoncode);
        }
        return sql.toString();
    }
    /**
     * @param paraMap
     * @return
     * @description: 参照查询方法
     * @author: xinfushuo
     * @date: 2022-02-22
     * @modify:
     */
    @Override
    @GetMapping(value = "/refList")
    public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
        return super.refList(paraMap);
    }

    /**
     * @param paraMap
     * @return
     * @description: 树查询方法
     * @author: xinfushuo
     * @date: 2022-02-22
     * @modify:
     */
    @GetMapping(value = "/queryTreeList")
    public ResponseResult<Object> queryTreeList(@RequestParam(required = false) Map<String, Object> paraMap) {
        String sqlWhere = this.spellListSql(paraMap);
        sqlWhere += " order by id asc";
        List<Map<String, Object>> listModule = this.service.queryMapByWhere(sqlWhere);
        for (int i = 0; i < listModule.size(); i++) {
            listModule.get(i).put("name", listModule.get(i).get("areaname"));
        }
        List<Map<String, Object>> listNewModule = new ArrayList<Map<String, Object>>();
        listNewModule.addAll(listModule);
        TreeModel treeModel = new TreeModel();
        List<TreeModel> treeList = treeModel.buildTree(listNewModule, true, "部门地市信息表树");
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("dataList", treeList);
        return ResponseResult.ok(dataMap);
    }

    /**
     * @param
     * @return
     * @throws
     * @description:
     * @author xinfushuo
     * @date 2022/2/23
     * @modify
     */
    @GetMapping(value = "/queryProvinceCityInfoByID")
    public ResponseResult<Object> queryProvinceCityInfoByID(@RequestParam(required = true) String id) {
        try {
            List<String> fieldList = new ArrayList<>();
            fieldList.add(MmsProvinceCityMatchinfoEntity.FieldLevelcode);
            fieldList.add(MmsProvinceCityMatchinfoEntity.FieldId);
            fieldList.add(MmsProvinceCityMatchinfoEntity.FieldArealevel);
            HashMap<String, Object> map = new HashMap<>();
            map.putAll(mmsProvinceCityMatchinfoService.queryFieldsById(id, fieldList));
            return ResponseResult.ok(map);
        } catch (Exception e) {
            return this.handleControllerException(e);
        }
    }

    /**
     * @param paraMap
     * @return
     * @description: 一级部门树查询方法
     * @author: hudeyong
     * @date: 2021-06-21
     * @modify:
     */
    @GetMapping(value = "/queryTreeListFromProvinceCityMatchInfo")
    public ResponseResult<Object> queryTreeListFromProvinceCityMatchInfo(@RequestParam(required = false) Map<String, Object> paraMap) {
        String depcommoncodeOfUser = this.service.getDeptCommonCode(getUserBean().getDept().getCode());
        List<TreeModel> treeList = this.service.queryTreeListForDeptProvince(depcommoncodeOfUser);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("dataList", treeList);
        return ResponseResult.ok(dataMap);
    }

    /**
     * @return
     * @throws
     * @description:
     * @author xinfushuo
     * @date 2022/2/25
     * @modify
     */
    @Override
    @GetMapping(value = "/dataCodeList")
    public ResponseResult<Object> dataCodeList(@RequestParam(required = false) Map<String, Object> paraMap) {
        Map<String, Object> codeMap = new HashMap<String, Object>();
        List<Map<String, Object>> deptcommoncodeList = datacodeCache.getCodeListMap("DeptCommonCode", "", "sortcode");
        codeMap.put("deptcommoncodeList", deptcommoncodeList);
        //添加非省区部门编码list
        List<Map<String, Object>> rangelist = datacodeCache.getCodeListMap(MmsSystemConst.DeptcommonProvinceViewRange, "", "sortcode");
        Map<String, String> rangeMap = rangelist.stream().collect(Collectors.toMap(map -> ConvertUtil.convertToString(map.get("code")), map -> ConvertUtil.convertToString(map.get("name"))));
        List<Map<String, Object>> notProvinceDeptcommoncodeList = new ArrayList<>();
        notProvinceDeptcommoncodeList.addAll(
                deptcommoncodeList.stream().filter(map -> rangeMap.containsKey(ConvertUtil.convertToString(map.get("code")))).collect(Collectors.toList())
        );
        List<Map<String, Object>> arealevelList = datacodeCache.getCodeListMap("AreaLevel", "", "sortcode");
        codeMap.put("arealevelList", arealevelList);
        List<Map<String, Object>> enabledList = datacodeCache.getCodeListMap("CboYesNo", "", "sortcode");
        codeMap.put("enabledList", enabledList);

        codeMap.put("notProvinceDeptcommoncodeList", notProvinceDeptcommoncodeList);
        super.dataCodeList(paraMap);
        return ResponseResult.ok(codeMap);
    }

    /**
     * @param
     * @return
     * @throws
     * @description:
     * @author xinfushuo
     * @date 2022/2/25
     * @modify
     */
    @Override
    protected void beforeInsert(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
        List<MmsDeptProvinceCityMatchInfoEntity> authList = this.service.queryByWhere(MmsDeptProvinceCityMatchInfoEntity.FieldParentid + " = " + paraMap.get(MmsDeptProvinceCityMatchInfoEntity.FieldParentid));
        String newDeptcommoncode = ConvertUtil.convertToString(paraMap.get(MmsDeptProvinceCityMatchInfoEntity.FieldDeptcommoncode));
        Boolean alreadyExisted = authList.stream().filter(entity -> {
            return entity.getDeptcommoncode().contentEquals(newDeptcommoncode);
        }).findAny().isPresent();
        if (alreadyExisted) {
            throw new BusinessException("该部门已存在区域授权列表中,请勿重复添加!\n如有需要请对已有数据进行编辑。");
        }
        List<String> usercodeList = new ArrayList<>(Arrays.asList(ConvertUtil.convertToString(dataMap.get(MmsDeptProvinceCityMatchInfoEntity.FieldUsercodes)).split(",")));
        String usercodes = usercodeList.stream().map(s -> "'".concat(s).concat("'")).collect(Collectors.joining(","));
        Map<String, Object> params = new HashMap<>();
        params.put("usercodes", usercodes);
        Boolean multipleDept = mmsDeptExtraInfoService.queryMap(params, "queryDeptcommoncodesByUsercodes").stream().filter(map -> !ConvertUtil.convertToString(map.get("deptcommoncode")).contentEquals(newDeptcommoncode)).findAny().isPresent();
        if (multipleDept) {
            throw new BusinessException("请勿添加非相同部门或者非授权部门的人员");
        }
    }

    @Override
    protected void beforeUpdate(Map<String, Object> dataMap, Map<String, Object> paraMap) throws Exception {
        String newDeptcommoncode = ConvertUtil.convertToString(paraMap.get(MmsDeptProvinceCityMatchInfoEntity.FieldDeptcommoncode));

        List<String> usercodeList = new ArrayList<>(Arrays.asList(ConvertUtil.convertToString(dataMap.get(MmsDeptProvinceCityMatchInfoEntity.FieldUsercodes)).split(",")));
        String usercodes = usercodeList.stream().map(s -> "'".concat(s).concat("'")).collect(Collectors.joining(","));
        Map<String, Object> params = new HashMap<>();
        params.put("usercodes", usercodes);
        Boolean multipleDept = mmsDeptExtraInfoService.queryMap(params, "queryDeptcommoncodesByUsercodes").stream().filter(map -> !ConvertUtil.convertToString(map.get("deptcommoncode")).contentEquals(newDeptcommoncode)).findAny().isPresent();
        if (multipleDept) {
            throw new BusinessException("请勿添加非相同部门或者非授权部门的人员");
        }
    }
}
